package edu.ustb.aur.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

/**
 * @author ShiZhe
 * @create 2021-11-04 16:02 MappedJdbcTypes：对应数据库类型 MappedTypes：java数据类型 类型转换器，用于数据库的varchar和Java中List<String>类型的相互转换
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListToVarcharTypeHandler implements TypeHandler<List<String>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
        throws SQLException {
        String hobbys = dealListToOneStr(parameter);
        ps.setString(i, hobbys);
    }

    /**
     * 集合拼接字符串
     * 
     * @param parameter
     *            参数
     * @return 结果
     */
    private String dealListToOneStr(List<String> parameter) {
        if (parameter == null || parameter.size() <= 0) {
            return null;
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < parameter.size(); i++) {
            if (i == parameter.size() - 1) {
                res.append(parameter.get(i));
                return res.toString();
            }
            res.append(parameter.get(i)).append(",");
        }
        return null;
    }

    @Override
    public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
        // 获取String类型的结果，使用","分割为List后返回
        return rs.getString(columnName) == null ? new ArrayList<String>()
            : Arrays.asList(rs.getString(columnName).split(","));
    }

    @Override
    public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getString(columnIndex) == null ? new ArrayList<String>()
            : Arrays.asList(rs.getString(columnIndex).split(","));
    }

    @Override
    public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getString(columnIndex) == null ? new ArrayList<String>()
            : Arrays.asList(cs.getString(columnIndex).split(","));
    }
}
